//
//  HSTabBarController.swift
//  HomeSchoolDemo
//
//  Created by Mac on 16/9/26.
//  Copyright © 2016年 chendong. All rights reserved.
//

import UIKit

class HSTabBarController: UITabBarController {

    //全局闭包属性
    var leftBtnBlock: (()->())?
    
    override func viewDidLoad() {
        super.viewDidLoad()
        //
        view.backgroundColor = #colorLiteral(red: 0.1764705926, green: 0.01176470611, blue: 0.5607843399, alpha: 1)
        //改变按钮字体选中颜色
        tabBar.tintColor = UIColor().colorWithHex(0x00a9e9)
        
        let dic = [["vc":"HSMessageController","title":"消息","imageName":"inform"],["vc":"HSHomeworkController","title":"作业","imageName":"homework"],["vc":"HSClassroomController","title":"课堂","imageName":"class_exercise"],["vc":"HSScoreController","title":"成绩","imageName":"examination"]]
        
        //添加子控制器
        for dict in dic{
            addChildController(dict)
        }
    }
    
    //重载添加方法封装
    //fileprivate 私有化 支持类延展
    //private完全私有 只在当前类方法中有效
    fileprivate func addChildController(_ dict: [String:String]) {
        //获得命名空间并将控制器名称转换类
        guard let bundleName = Bundle.main.bundleName,
        let imageName = dict["imageName"],
        let vcName = dict["vc"],
        let cls = NSClassFromString("\(bundleName).\(vcName)") as? UIViewController.Type else {
            return
        }
        //使用反射机制，将字符串转换为类型
        let childController = cls.init()

        //标题
        childController.title = dict["title"]
        //nomal图片
        childController.tabBarItem.image = UIImage(named: "\(imageName)_nor")
        //设置字体大小
        childController.tabBarItem.setTitleTextAttributes([NSFontAttributeName:UIFont.systemFont(ofSize: 14 )], for: .normal)
        //select图片
        childController.tabBarItem.selectedImage = UIImage(named: "\(imageName)_press")?.withRenderingMode(.alwaysOriginal)
        //添加左边按钮
        
        childController.navigationItem.leftBarButtonItem = UIBarButtonItem(imageName: "icon_menu_nor", bgImageName: "icon_menu_press", target: self, action: #selector(leftBtnClicked))
        //包装一个导航控制器
        let navVC = HSNavigationController(rootViewController: childController)
        //添加
        addChildViewController(navVC)
    }
    
    @objc fileprivate func leftBtnClicked() {
        //执行闭包，传递点击事件
        leftBtnBlock?()
    }
    
}
